package fr.lelouet.monitoring.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import fr.lelouet.monitoring.DataHandler;
import fr.lelouet.monitoring.UsageMonitor;
import fr.lelouet.monitoring.perf.Tools;
import fr.lelouet.plugwise.IDevice;
import fr.lelouet.plugwise.python.PythonDevice;

class PlugwisedHypervisor implements UsageMonitor{
	
	public static final String PLUGWISE_USBPATH_KEY="plugwise.usbpath"
	
	private final static Logger logger = LoggerFactory.getLogger(PlugwisedHypervisor.class)
	
	String usbPath="/dev/ttyUSB0"
	String macAdress=""
	protected IDevice plugwise = new PythonDevice(id:"")
	public void setMacAdress(String adress) {
		this.macAdress = adress
		plugwise.setId(adress)
	}
	
	public PlugwisedHypervisor(String mac) {
		this.macAdress = mac;
	}
	
	public String getId() {
		return "localhost"
	}
	
	/** the key to store the plugwise consumption with*/
	public static final String CONSUMPTION_NAME="plugwise.consumption"
	
	/** the key to store the plugwise mac with*/
	public static final String PLUGWISEMAC_NAME="plugwise.mac"
	
	public void gatherInformations() {
		gatherSuccessful=false
		Thread.start {
			try {
				Map map = [:]
				map[PLUGWISEMAC_NAME] = macAdress
				Float consumption = plugwise.getInstantConsumption()
				if(consumption>=0) {
					map[CONSUMPTION_NAME] = consumption.toString()
					Tools.timeMap map
					Tools.markHypervisor map, getId()
					handlers.each { ((DataHandler)it).handle(map) }
				}
			} catch(Exception e) {
				logger.warn("{} @ {}", e, e.getStackTrace()[0])
			}
			gatherSuccessful=true
		}
	}
	
	public void configure(Properties prop) {
		//XXX should use same properties as the KvmHypervisor
		String path = prop.getProperty(PLUGWISE_USBPATH_KEY)
		if(path!=null) {
			usbPath= path;
			logger.info("plugwisedHypervisor for "+macAdress+" linked to usb "+usbPath)
		}
	}
	
	protected List<DataHandler> handlers = []
	public void setHandlers(List<DataHandler> handlers) {
		this.handlers=handlers
	}
	
	public void interrupt() {
		//TODO
		throw new UnsupportedOperationException()
	}
	
	protected boolean gatherSuccessful = true;
	public boolean informationGathered() {
		return gatherSuccessful
	} 
	
	static main(args) {
		println(PlugwisedHypervisor.getConsumption("/dev/ttyUSB0", "000D6F000076A98E"))
	}
}
